import CryptoJS from "crypto-js"

// 接口加密密钥
let VUE_APP_API_CRYPT_KEY = 'J8s47P99AR2G2TFa85LjYawD87g6599r'

const CRYPT_KEY = VUE_APP_API_CRYPT_KEY

function getCryptOption() {
    return {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    }
}

// 加密
export function encrypt(context, keyStr = CRYPT_KEY) {
    try {
        const key = CryptoJS.enc.Utf8.parse(keyStr)
        const src = CryptoJS.enc.Utf8.parse(context)
        const words = CryptoJS.AES.encrypt(src, key, getCryptOption())
        return words.toString()
    } catch (error) {
        console.error(error)
        return null
    }
}

// 解密
export function decrypt(context, keyStr = CRYPT_KEY) {
    try {
        const key = CryptoJS.enc.Utf8.parse(keyStr)
        const decrypted = CryptoJS.AES.decrypt(context, key, getCryptOption())
        return CryptoJS.enc.Utf8.stringify(decrypted).toString()
    } catch (error) {
        console.error(error)
        return null
    }
}
